package com.knowledge.graph.service;

import com.knowledge.graph.mapper.UserMapper;
import com.knowledge.graph.model.entity.User;
import com.knowledge.graph.model.vo.ResponseVO;
import com.knowledge.graph.model.vo.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

@Service
public class UserService {

    private static final String SAIL = "zhishitupu";
    @Autowired
    UserMapper userMapper;

    public ResponseVO queryUser(String userName, String passWord, HttpServletRequest httpServletRequest) {
        String encryptPassWord = DigestUtils.md5DigestAsHex((SAIL + passWord).getBytes());
        User queryUser = userMapper.selectByUserName(userName);
        if (queryUser == null) {
            User user = new User(userName, encryptPassWord);
            int flag = userMapper.insert(user);
            if (flag == 1) {
                httpServletRequest.getSession().setAttribute("user_state", user);
                return new ResponseVO<>(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMessage(),user);
            } else {
                return new ResponseVO(StatusCode.FAIL_ADD.getCode(), StatusCode.FAIL_ADD.getMessage());
            }
        } else if (!encryptPassWord.equals(queryUser.getPassword())) {
            return new ResponseVO(StatusCode.FAIL_SELECT.getCode(), StatusCode.FAIL_SELECT.getMessage());
        }
        httpServletRequest.getSession().setAttribute("user_state", queryUser);
        return new ResponseVO<>(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMessage(),queryUser);
    }
}
